
package heman.server.controllers;




import heman.server.database.DatabaseController;
import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import ks.framework.common.Message;
import ks.framework.communicator.Communicator;

import ks.server.interfaces.IProcessServerMessage;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * 
 *  Controller to handle playerInfo request. 
 *  
 *   <xs:element name="playerInfo">
- <xs:complexType>
  <xs:attribute name="password" type="xs:string" use="required" /> 
  <xs:attribute name="new-realName" type="xs:string" use="optional" /> 
  <xs:attribute name="new-password" type="xs:string" use="optional" /> 
  </xs:complexType>
  </xs:element>

 *    A playerResponse message will be broadcast.
 *    @author Wenlong Liu
 *  */

public class PlayerInfoController implements IProcessServerMessage {

	public boolean process(Communicator com, Message m) {
		String originator=m.getOriginator();
		
       
        Node root = m.contents();
        NamedNodeMap map=root.getAttributes();

        Node pwNode=map.
        		getNamedItem("password");
        Node newPwNode=map.getNamedItem("new-password");
        Node realNameNode=map.getNamedItem("new-realName");
        String stringPwd=pwNode.getNodeValue();
        if (pwNode==null) return false;
        //authorize
        if (!DatabaseController.getPsw(originator).equals(pwNode.getNodeValue())) return false;
        //String tempString=newPwNode.getNodeValue();
        //Change the password
        if (newPwNode!=null){
        	String pwdString=newPwNode.getNodeValue();
        	if (!DatabaseController.updatePwd(originator, newPwNode.getNodeValue())) return false;
        	
        }
        //Change the real name
        Player player=PlayerManager.getInstance().getPlayer(originator);
        if (player == null) return false;
        
        if (realNameNode!=null){
        	player.setName(realNameNode.getNodeValue());
        	if (!DatabaseController.updatePlayer(player)) return false;
        	//DatabaseController.updateRealName(originator, );
        	
        }
        
        //Send playerResponse to all players online
		
        
        // produce successful request. note that client is responsible 
        // now for tagging from.
        StringBuilder sb = new StringBuilder(Message.responseHeader(true,m.id));
        //sb.append("")
        sb.append("<playerResponse>");
        
        sb.append(player.toXMLPlayer());
        sb.append("</playerResponse></response>");
        String string=sb.toString();
        Document d = Message.construct(sb.toString());
        
        Message r = new Message (d);
        r.setOriginator(originator);
        r.setRecipient(originator);
        r.setBroadcast();

        return com.distribute(r);
        
        
       
        	
      
        
	}
}